import { asyncRouterMap, constantRouterMap } from '@/router'

/**
 * 递归过滤异步路由表，返回符合用户角色权限的路由表
 * @param routes asyncRouterMap
 * @param hisRoutes 角色路由名称信息
 */
function filterAsyncRouter(routes, hisRoutes) {
  const res = []
  routes.forEach(route => {
    const tmp = { ...route }
    if (hisRoutes.some(routename => routename === tmp.meta.title)) {
      if (tmp.children) {
        tmp.children = filterAsyncRouter(tmp.children, hisRoutes)
      }
      res.push(tmp)
    }
  })
  return res
}

/**
 * 递归统计所有路由title
 * @param routes
 */
function getRouteTitles(routes) {
  // const res = []
  // routes.forEach(route => {
  //   if (route.meta.type !== 'base') {
  //     res.push(route.meta.title)
  //     if (route.children) {
  //       res.concat(getRouteTitles(route.children))
  //     }
  //   }
  // })
  // return res
  const res = []
  routes.forEach(route => {
    res.push(route.meta.title)
    if (route.children) {
      res.concat(getRouteTitles(route.children))
    }
  })
  return res
}

const permission = {
  state: {
    routers: constantRouterMap,
    route_titles: [],
    addRouters: []
  },
  mutations: {
    SET_ROUTERS: (state, routers) => {
      routers = routers.concat({ path: '*', redirect: '/404', hidden: true, meta: { type: 'base' }})
      state.addRouters = routers
      state.routers = constantRouterMap.concat(routers)
    },
    SET_ROUTE_TITLES: (state, routes) => {
      state.route_titles = getRouteTitles(asyncRouterMap)
    }
  },
  actions: {
    GenerateRoutes({ commit }, data) {
      return new Promise(resolve => {
        const { routes } = data
        const accessedRouters = filterAsyncRouter(asyncRouterMap, routes)
        commit('SET_ROUTERS', accessedRouters)
        commit('SET_ROUTE_TITLES', constantRouterMap.concat(asyncRouterMap))
        resolve()
      })
    }
  }
}

export default permission
